package com.webchat.chat.service;

import com.corundumstudio.socketio.BroadcastOperations;
import com.corundumstudio.socketio.SocketIOServer;
import com.github.pagehelper.PageInfo;
import com.webchat.chat.core.dto.evenMessage.MsgInfo;
import com.webchat.chat.core.enums.MsgType;
import com.webchat.chat.core.tools.SocketConstant;
import com.webchat.chat.model.ChatRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Owner on 2018/7/16.
 */
@Service
public class ChatRecordMGService {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Resource
    private SocketIOServer socketIOServer;


    public void save(ChatRecord chatRecord) {

        mongoTemplate.save(chatRecord);
    }


    public List<ChatRecord> findByContentLikeAndTenantCode(String content, String tenanteCode) {
        Query query = getQuery(null,null,tenanteCode);
        query.addCriteria(Criteria.where("content").regex(content));
        return mongoTemplate.find(query, ChatRecord.class);
    }

    public List<ChatRecord> findByConditions(ChatRecord chatRecord, Integer page, Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "time");
        Query query =getQuery(page,size,chatRecord.getTenantCode());

        if (!"".equals(chatRecord.getSourceUserName())) {
            query.addCriteria(Criteria.where("sourceUserName").is(chatRecord.getSourceUserName()));
        }
        if (!"".equals(chatRecord.getTargetUserName())){
            query.addCriteria(Criteria.where("targetUserName").is(chatRecord.getTargetUserName()));
        }
        if (null != chatRecord.getFileType()){
            query.addCriteria(Criteria.where("fileType").exists(true));
        }else{
            query.addCriteria(Criteria.where("fileType").exists(false));
        }
        if (!"".equals(chatRecord.getContent())){
            query.addCriteria(Criteria.where("content").regex(chatRecord.getContent()));
        }

        List<ChatRecord> chatRecords = mongoTemplate.find(query.with(sort), ChatRecord.class);
        return chatRecords;
    }


    public List<ChatRecord> findByRoomIdAndTenantCode(String roomId,Integer page, Integer size, Date time) {
        Sort sort = Sort.by(Sort.Direction.DESC, "time");

        Query query = getQuery(null,null,null);
        query.addCriteria(Criteria.where("roomId").is(roomId));
        Calendar calendar = Calendar.getInstance();
        calendar.add(calendar.DATE,-1);
        query.addCriteria(Criteria.where("time").lt(time).gt(calendar.getTime()));
        List<ChatRecord> chatRecords = mongoTemplate.find(query.with(sort), ChatRecord.class);
        return chatRecords;
    }

    public boolean messagePassAudit(String[] chatRecordIds, String tenantCode) {
        Query query = getQuery(null,null,tenantCode);
        query.addCriteria(Criteria.where("id").in(chatRecordIds));
        List<ChatRecord> chatRecords = mongoTemplate.find(query, ChatRecord.class);
        chatRecords.forEach( e -> {
            if (e.getAuditStatus()){
                String roomId = e.getRoomId();
                BroadcastOperations roomOperations = socketIOServer.getRoomOperations(roomId);
                if (roomOperations == null) {
                    return;
                }
                MsgInfo msg = e.getMsg();
                msg.setMsgType(MsgType.审核通过消息);
                roomOperations.sendEvent(SocketConstant.CS_CHAT_C, msg);
                e.setMsg(msg);
                e.setAuditStatus(false);
            }
        });
        mongoTemplate.updateMulti(query, Update.update("auditStatus", false), ChatRecord.class);

        return true;
    }

    public PageInfo findNeedAuditMessage(Integer page, Integer size, String tenantCode) {
        Query query = getQuery(page,size,null);
        Sort sort = Sort.by(Sort.Direction.DESC, "time");
        query.addCriteria(Criteria.where("auditStatus").is(true));
        List<ChatRecord> chatRecords = mongoTemplate.find(query.with(sort), ChatRecord.class);

        PageInfo pageInfo = new PageInfo(chatRecords);
        pageInfo.setTotal(mongoTemplate.count(query, ChatRecord.class));
        return pageInfo;
    }

    private Query getQuery(Integer page, Integer size,String tenantCode) {
        Query query = new Query();
        if (null != page && null != size){
            query.skip((page - 1) * size);
            query.limit(size);
        }
        if(null != tenantCode && !"".equals(tenantCode)){
            if ("All".equals(tenantCode)){
                query.addCriteria(Criteria.where("tenantCode").exists(true));
            }else {
                query.addCriteria(Criteria.where("tenantCode").is(tenantCode));
            }
        }
        return query;
    }


}




